package com.codebyorder.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codebyorder.entity.User;
import com.codebyorder.exception.BusinessException;
import com.codebyorder.exception.BusinessExceptionCode;
import com.codebyorder.mapper.UserMapper;
import com.codebyorder.req.UserLoginReq;
import com.codebyorder.req.UserQueryReq;
import com.codebyorder.resp.PageResp;
import com.codebyorder.resp.UserLoginResp;
import com.codebyorder.resp.UserQueryResp;
import com.codebyorder.service.UserService;
import com.codebyorder.util.CopyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 29038
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2022-12-16 08:47:49
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;
    private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);


    @Override
    public PageResp<UserQueryResp> userToResp(UserQueryReq userQueryReq) {
        PageHelper.startPage(userQueryReq.getPage(), userQueryReq.getSize());//和第一个查询语句放在一起,请求参数
        List<User> users = userMapper.selectByName(userQueryReq.getLoginName());

        PageInfo<User> pageInfo = new PageInfo<>(users);
        LOG.info("总行数:{}", pageInfo.getTotal());//返回给前端
        LOG.info("总页数:{}", pageInfo.getPages());

        List<UserQueryResp> userResp = CopyUtil.copyList(users, UserQueryResp.class);
        PageResp<UserQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(userResp);
        return pageResp;
    }

    @Override
    public UserLoginResp login(UserLoginReq userLoginReq) {
        User userDB = userMapper.selectByLoginName(userLoginReq.getLoginName());
        if (ObjectUtils.isEmpty(userDB)) {
            LOG.info("用户名不存在, {}", userLoginReq.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        } else if (userDB.getPassword().equals(userLoginReq.getPassword())) {
            return CopyUtil.copy(userDB,UserLoginResp.class);
        } else {
            LOG.info("密码不对, 输入密码：{}, 数据库密码：{}", userLoginReq.getPassword(), userDB.getPassword());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }
    }
}




